package guoanmaker.operator.business.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import org.springframework.stereotype.Service;

import guoanmaker.operator.business.dao.OperatorActiveTaskDao;
import guoanmaker.operator.business.model.OperatorActiveChance;
import guoanmaker.operator.business.model.OperatorActiveTask;
import guoanmaker.operator.business.model.ProvideOrderForm;
import guoanmaker.operator.business.model.ReturnResult;
import guoanmaker.operator.business.modelnobind.OperatorActiveTaskVO;
import guoanmaker.operator.business.modelnobind.OperatorEventDetailsOptions;
import guoanmaker.operator.business.repository.OperatorActiveChanceRepository;
import guoanmaker.operator.business.repository.OperatorActiveTaskRepository;
import guoanmaker.operator.business.repository.OperatorActiveTaskTypeRepository;
import guoanmaker.operator.business.repository.OperatorEventDetailsRepository;
import guoanmaker.operator.business.repository.ProvideOrderFormRepository;
import guoanmaker.operator.helper.common.util.ActiveURLUtil;

/**
 * 
 * @author ws
 * @date 2017-11-23
 */
@Service
public class OperatorActiveTaskService implements OperatorActiveTaskServiceInterface {

	@Resource
	private OperatorActiveTaskDao operatorActiveTaskDao;
	
	@Resource
	private OperatorActiveTaskRepository operatorActiveTaskRepository;
	
	@Resource
	private OperatorActiveTaskTypeRepository operatorActiveTaskTypeRepository;
	
	@Resource
	private OperatorEventDetailsRepository operatorEventDetailsRepository; 
	
	@Resource
	private OperatorActiveChanceRepository operatorActiveChanceRepository;
	
	@Resource
	private ProvideOrderFormRepository provideOrderFormRepository;
	
	@Resource
	private OperatorSendMesToCusServiceIntegerface operatorSendMesToCusService;
	/**
	 * @description: 从表t_operator_event_details中根据luck_name and activity_type_id  and availability查询记录
	 * @param availability
	 * @param activityTypeId
	 * @param luckName
	 * @return id, eventTitle两个字段
	 */
	public List<OperatorEventDetailsOptions> findOperatorEventDetailsByAvailabilityAndActivityTypeIdAndLuckName(String availability, String activityTypeId, String luckName) {
		
		availability = availability.trim();
		activityTypeId = activityTypeId.trim(); 
		luckName = luckName.trim();
	
		return operatorActiveTaskDao.findOperatorEventDetailsByAvailabilityAndActivityTypeIdAndLuckName(availability, activityTypeId, luckName);
		
	}

	/**
	 * @description:新增或修改任务记录
	 * @param taskId 任务id
	 * @param taskName 任务名称
	 * @param taskTypeId 任务类型id
	 * @param taskAmount 订单金额
	 * @param activeId 活动id
	 * @return ReturnResult
	 */
	@Override
	@Transactional
	public ReturnResult saveOrUpdateOperatorActiveTask(String taskId, String taskName, String taskTypeId, String taskAmount, String activeId) {
		ReturnResult returnResult = new ReturnResult();
		
		if(taskName == null || taskName.trim().length() == 0){
			returnResult.setKey("error");
			returnResult.setValue("任务名称为空");
			return returnResult;
		}
		taskName = taskName.trim();
		//同一任务类型下，任务名称不能重复
		if(operatorActiveTaskDao.countSameTaskName(taskId, taskName, taskTypeId) > 0){
			returnResult.setKey("error");
			returnResult.setValue("已存在相同任务名");
			return returnResult;
		}
		
		
		if(taskAmount == null || taskAmount.trim().length() == 0){
			returnResult.setKey("error");
			returnResult.setValue("订单金额为空");
			return returnResult;
		}
		taskAmount = taskAmount.trim();
		//同一任务类型下，订单金额不能重复
		if(operatorActiveTaskDao.countSameTaskAmount(taskId, taskAmount, taskTypeId) > 0){
			returnResult.setKey("error");
			returnResult.setValue("已存在相同的订单金额");
			return returnResult;
		}
		
		//若任务id存在,则修改表中数据;否则新增表数据
		OperatorActiveTask task = null;
		if(taskId != null && taskId.trim().length() >0){
			task = operatorActiveTaskRepository.findOne(taskId);
		} else{
			task = new OperatorActiveTask();
		}
		task.setActiveTaskName(taskName);
		task.setActiveTaskType(operatorActiveTaskTypeRepository.findOne(taskTypeId));
		task.setActiveTaskAmount(taskAmount);
		task.setDateTime(new Date());
		task.setActive(operatorEventDetailsRepository.findOne(activeId));
		operatorActiveTaskRepository.save(task);
		returnResult.setKey("success");
		returnResult.setValue("操作成功");
		
		return returnResult;
	}

	/**
	 * @description:根据任务id删除任务记录
	 * @param taskId 任务id
	 * @return void
	 */
	@Override
	@Transactional
	public void deleteOperatorActiveTaskById(String taskId) {
		operatorActiveTaskRepository.deleteById(taskId.trim());
	}
	
	/**
	 * @descrption:根据活动名称和活动类型分页查询
	 * @param taskName 任务名称
	 * @param taskTypeId 任务类型id
	 * @param page 当前页
	 * @param size 当前页显示记录的数量
	 * @return
	 */
	@Override
	public Map<String, Object> findByTaskNameAndTaskType(String taskName, String taskTypeId, String page,String size) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		long total = operatorActiveTaskDao.totalByTaskNameAndTaskType(taskName, taskTypeId);
		List<OperatorActiveTaskVO> resultList = operatorActiveTaskDao.findByTaskNameAndTaskType(taskName, taskTypeId, page, size);
		resultMap.put("total", total);
		resultMap.put("list", resultList);
		return resultMap;
	}

	/**
	 * @description:根据订单中的实付金额-优惠金额查询和任务类型id对应的活动url,并添加或修改t_operator_active_chance
	 * @param provideOrderFormId 订单id
	 * @param taskTypeId 任务类型id
	 * @return String url地址
	 */
	@Override
	@Transactional
	public String findActiveURLByTruePriceAndTaskTypeId(String provideOrderFormId, String taskTypeId) {
		Map<String, String> map = operatorActiveTaskDao.findActiveIdAndLuckNameByTruePriceAndTaskTypeId(provideOrderFormId, taskTypeId);
		
		if(map == null){
			return null;
		}
		
		String result = null;
		String activeId = map.get("id");
		String luckName = map.get("luckName");
		
		boolean flag = false;//判断是否返回了活动id
		if("大转盘".equals(luckName) && activeId != null && activeId.trim().length() != 0){
			result = ActiveURLUtil.getPath("ferris_wheel")+activeId;
			flag = true;
		}
		if("砸金蛋".equals(luckName) && activeId!= null && activeId.trim().length() != 0){
			result = ActiveURLUtil.getPath("egg_frenzy")+activeId;
			flag = true;
		}
		if(flag){
			//根据订单id获得userId
			ProvideOrderForm provideOrderForm = provideOrderFormRepository.findOne(provideOrderFormId);
			String userId = provideOrderForm.getUser().getId();
					
			//向t_operator_active_chance添加或修改记录.若根据active_id和user_id查找记录，若存在则number字段加一；否则添加记录，number为1
			OperatorActiveChance oac = operatorActiveChanceRepository.queryActiveChanceByuserId(userId, activeId);
			if(oac == null){
				oac = new OperatorActiveChance();
				oac.setActiveId(activeId);
				oac.setUserId(userId);
				oac.setNumber(1);
			} else{
				oac.setNumber(oac.getNumber()==null?0:oac.getNumber() + 1);
			}
			operatorActiveChanceRepository.save(oac);
			
			String orderNumber = provideOrderForm.getOrderNumber();
			operatorSendMesToCusService.sendPayFor(result+"&userId="+userId, userId, orderNumber);
			
			return result;
		}
		
		return null;
	}

}
